# -*- coding: utf-8 -*-
"""
@Time    : 2022/8/29 17:21
@Author  : huanghuang
"""
import io
from typing import Union
from starlette.requests import Request
import pyqrcode

from common.pkg.str_id import get_short_uuid
from common.g.g import G_SETTINGS


def get_real_ip(request: Request):
    return request.headers.get("X-REAL-IP") or request.client.host


def get_byte_content(filepath):
    with open(filepath, "rb") as f:
        content = f.read()
    bio = io.BytesIO()
    bio.write(content)
    return bio


def generate_qrcode(content: str,
                    filename: str = None,
                    scale: int = 8,
                    need_bytes: bool = False) -> Union[str, io.BytesIO]:
    filename = filename or f'{G_SETTINGS.static_root}/{get_short_uuid("qrcode_")}.png'
    pyqrcode.create(content).png(filename, scale=scale)
    if need_bytes:
        return get_byte_content(filename)
    return filename


if __name__ == '__main__':
    print(generate_qrcode("https://www.baidu.com", need_bytes=True))
